package com.music.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.music.common.BaseResult;
import com.music.dao.CmUserDaoMapper;
import com.music.entity.CmUser;
import com.music.entity.req.CmUserReq;
import com.music.entity.req.CmVipReq;
import com.music.entity.req.VipTime;
import com.music.service.CmUserService;
import com.music.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 2 * @Author: 刘佳乐 :面向百度编程
 * 3 * @Date: 2020/12/13 14:29
 * 4
 */
@Service
public class CmUserServiceImpl implements CmUserService {

    @Autowired
    private CmUserDaoMapper cmUserDaoMapper;

    @Autowired
    private RedisUtils redisUtils;

    public String getToken(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String number=null;
        for (Cookie cook:cookies
        ) {
            if (cook.getName().equals("token")){
                number=cook.getValue();
            }
        }
        return number;
    }

    @Override
    public BaseResult findAll() {
        BaseResult baseResult = new BaseResult();
        List<CmUser> all = cmUserDaoMapper.findAll();
        if(all!=null){
            baseResult.setData(all);
            baseResult.setCode(200);
            baseResult.setMessage("查询成功");
            return baseResult;
        }
        baseResult.setCode(201);
        baseResult.setMessage("查询失败");
        return baseResult;
    }

    @Override
    public BaseResult findByTel(String uTel) {
        BaseResult baseResult = new BaseResult();
        CmUser byTel = cmUserDaoMapper.findByTel(uTel);
        if(byTel!=null){
            baseResult.setData(byTel);
            baseResult.setCode(200);
            baseResult.setMessage("查询成功");
            return baseResult;
        }
        baseResult.setCode(201);
        baseResult.setMessage("查询失败");
        return baseResult;
    }

    @Override
    public BaseResult findByuID(Integer uId) {
        BaseResult baseResult = new BaseResult();
        CmUser byuID = cmUserDaoMapper.findByuID(uId);
        if(byuID!=null){
            baseResult.setData(byuID);
            baseResult.setCode(200);
            baseResult.setMessage("查询成功");
            return baseResult;
        }
        baseResult.setCode(201);
        baseResult.setMessage("查询失败");
        return baseResult;
    }

    @Override
    public BaseResult sendCode(String uTel) {
        Map<String,Object> map=new HashMap<>();
        BaseResult baseResult=new BaseResult();
        if(uTel!=null){
            //连接阿里云
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GK387fYKKHVD9tXmz19", "iiyIQLeOx13UqwuQoen9yH5AWK8SKI");
            IAcsClient client = new DefaultAcsClient(profile);

            //构建请求
            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");

            //自定义参数（手机号  签名 模板  验证码）
            request.putQueryParameter("PhoneNumbers", uTel);
            request.putQueryParameter("SignName", "阿乐跑腿");
            request.putQueryParameter("TemplateCode", "SMS_205449875");
            //构建一个短信验证码
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String code = uuid.substring(0, 4);
            map.put("code",code);
            request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
            redisUtils.set("code"+"_"+uTel,code,300);
            try {
                CommonResponse response = client.getCommonResponse(request);
                System.out.println(response.getData());
                baseResult.setMessage("短信验证码发送成功");
                baseResult.setCode(200);
                return baseResult;
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
        baseResult.setCode(201);
        baseResult.setMessage("不是正确的手机号");
        return baseResult;
    }

    @Override
    public BaseResult registry(CmUserReq cmUserReq) {
       BaseResult baseResult=new BaseResult();
        String substring = redisUtils.get("code_" + cmUserReq.getuTel()).toString();
        if(cmUserReq.getCode()!=null && cmUserReq.getCode().equalsIgnoreCase(substring)){
            CmUser cmUser=new CmUser();
            BeanUtils.copyProperties(cmUserReq,cmUser);
            CmUser byName = cmUserDaoMapper.findByTel(cmUser.getuTel());
            if(byName==null){
                int registry = cmUserDaoMapper.registry(cmUser);
                if(registry==1){
                    baseResult.setCode(200);
                    baseResult.setMessage("添加成功");
                    baseResult.setData(cmUser);
                    return baseResult;
                }else {
                    baseResult.setCode(201);
                    baseResult.setMessage("添加失败");
                    return baseResult;
                }
            }else {
                baseResult.setCode(202);
                baseResult.setMessage("该手机号已被注册");
                return baseResult;
            }
        }
        baseResult.setCode(203);
        baseResult.setMessage("验证码输入错误");
        return baseResult;
    }

    @Override
    public BaseResult login(CmUser cmUser) {
        BaseResult baseResult=new BaseResult();
//        CmUser login = cmUserDaoMapper.login(cmUser);
        CmUser byTel = cmUserDaoMapper.findByTel(cmUser.getuTel());
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        if(byTel!=null){
            if(cmUser.getuPass().equals(byTel.getuPass())){
                redisUtils.set(s,byTel);
                baseResult.setCode(200);
                baseResult.setMessage("登陆成功");
                baseResult.setData(s);
                return baseResult;
            }else{
                baseResult.setCode(201);
                baseResult.setMessage("密码输入错误");
                return baseResult;
            }
        }
        baseResult.setCode(202);
        baseResult.setMessage("当前手机号未被注册");
        return baseResult;
    }

    /**
     *
     * 开会员  改变数据库状态  用手机号作为key值存入redis
     * */
    @Override
    public BaseResult updatestatus(Integer uId, Integer month) {
        int i = cmUserDaoMapper.updatestatus(uId);
        BaseResult baseResult=new BaseResult();
        if(i==1){
            CmUser byuID = cmUserDaoMapper.findByuID(uId);
            if(month==1){
                redisUtils.set(byuID.getuTel(),byuID,60*60*24*30);
            }else if(month==2){
                redisUtils.set(byuID.getuTel(),byuID,60*60*24*30*3);
            }
            baseResult.setCode(200);
            baseResult.setMessage("修改成功");
            return baseResult;
        }
        baseResult.setCode(201);
        baseResult.setMessage("修改失败");
        return baseResult;
    }

    @Override
    public BaseResult buyVip(CmVipReq cmVipReq) {
        Integer uId = cmVipReq.getuId();
        Integer month = cmVipReq.getTime();
        int i = cmUserDaoMapper.updatestatus(uId);
        BaseResult baseResult=new BaseResult();
        if(i==1){
            CmUser byuID = cmUserDaoMapper.findByuID(uId);
            if(month==1){
                redisUtils.set(byuID.getuTel(),byuID,60*60*24*30);
            }else if(month==3){
                redisUtils.set(byuID.getuTel(),byuID,60*60*24*30*3);
            }
            baseResult.setCode(200);
            baseResult.setMessage("修改成功");
            return baseResult;
        }
        baseResult.setCode(201);
        baseResult.setMessage("修改失败");
        return baseResult;
    }

    /**
     * 查询用户是否是会员的方法  并且返回用户信息
     *
     * */

    @Override
    public BaseResult deletestatus(Integer uId) {
        BaseResult baseResult=new BaseResult();
        CmUser byuID = cmUserDaoMapper.findByuID(uId);
        Object o = redisUtils.get(byuID.getuTel());
        String s = JSONObject.toJSONString(o);
        CmUser cmUser = JSON.parseObject(s, CmUser.class);
        if(o==null){
            int deletestatus = cmUserDaoMapper.deletestatus(uId);
            if(deletestatus==1){
                CmUser byuID1 = cmUserDaoMapper.findByuID(uId);
                redisUtils.set(byuID.getuTel(),byuID);
                baseResult.setData(byuID1);
                return baseResult;
            }
        }
        baseResult.setData(cmUser);
        return baseResult;
    }

    @Override
    public BaseResult updatepass(CmUser cmUser) {
        int i = cmUserDaoMapper.updatepass(cmUser);
        BaseResult baseResult=new BaseResult();
        if(i==1){
            baseResult.setData(cmUser);
            baseResult.setCode(200);
            baseResult.setMessage("修改成功，请重新登录");
            return baseResult;
        }
        baseResult.setCode(201);
        baseResult.setMessage("修改失败");
        return baseResult;
    }
    @Override
    public BaseResult finAllByFriend() {
        BaseResult baseResult = new BaseResult();
        List<CmUser> allByFriend = cmUserDaoMapper.finAllByFriend();
        if(allByFriend!=null){
            baseResult.setData(allByFriend);
            baseResult.setCode(200);
            baseResult.setMessage("查询成功");
            return baseResult;
        }else{
            baseResult.setCode(201);
            baseResult.setMessage("查询失败");
            return baseResult;
        }

    }
    @Override
    public BaseResult updatemyhomepage(CmUser cmUser) {
        BaseResult baseResult = new BaseResult();
        Integer cmUser1 = cmUserDaoMapper.updatemyhomepage(cmUser);
        if (cmUser1==1){
            baseResult.setCode(200);
            baseResult.setMessage("修改成功");
            return baseResult;
        }
        baseResult.setCode(201);
        baseResult.setMessage("修改失败");
        return baseResult;
    }
}
